package com.negative.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

public class Utils {

	public static String tr2nl(String html) {
        if(html==null)return html;
        html.replaceAll("<tr>", "<br>");
        html.replaceAll("</tr>", "</br>");
        Document document = Jsoup.parse(html);
        document.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
        document.select("br").append("\\n");
//        document.select("p").prepend("\\n\\n");
        String s = document.html().replaceAll("\\\\n", "\n");
        return Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
    }
	
	public static String br2nl(String html) {
        if(html==null)return html;
        Pattern p = Pattern.compile("<tr>");
        Matcher m = p.matcher(html);
        html = m.replaceAll("<br>");
        p = Pattern.compile("</tr>");
        m = p.matcher(html);
        html = m.replaceAll("</br>");
        Document document = Jsoup.parse(html);
        document.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
        document.select("br").append("\\n");
//        document.select("p").prepend("\\n\\n");
        String s = document.html().replaceAll("\\\\n", "\n");
        return Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
    }

	public static String cleanHtml(String text) {
		return fixQuote(remWhiteSpaces(br2nl(text)));
	}

	private static String fixQuote(String text) {
		Pattern p = Pattern.compile("&quot;");
		Matcher m = p.matcher(text);
		
		return m.replaceAll("\"");
	}

	private static String remWhiteSpaces(String text) {
		Pattern p = Pattern.compile("&nbsp;");
		Matcher m = p.matcher(text);
		
		return m.replaceAll(" ");
	}
}
